<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房源标题" prop="propertyTitle">
        <el-input
          v-model="queryParams.propertyTitle"
          placeholder="请输入房源标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入省份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区县" prop="district">
        <el-input
          v-model="queryParams.district"
          placeholder="请输入区县"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="街道" prop="street">
        <el-input
          v-model="queryParams.street"
          placeholder="请输入街道"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="月租金" prop="monthlyRent">
        <el-input
          v-model="queryParams.monthlyRent"
          placeholder="请输入月租金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="面积(㎡)" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入面积(㎡)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卧室数量" prop="bedroomCount">
        <el-input
          v-model="queryParams.bedroomCount"
          placeholder="请输入卧室数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客厅数量" prop="livingroomCount">
        <el-input
          v-model="queryParams.livingroomCount"
          placeholder="请输入客厅数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="朝向" prop="orientation">
        <el-input
          v-model="queryParams.orientation"
          placeholder="请输入朝向"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房东姓名" prop="landlordName">
        <el-input
          v-model="queryParams.landlordName"
          placeholder="请输入房东姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:property:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:property:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading" class="property-list">
      <div class="property-card" v-for="property in propertyList" :key="property.propertyId">
        <!-- 左侧图片 -->
        <div class="property-image">
          <el-image
            :src="getCoverImage(property)"
            fit="cover"
            :preview-src-list="getAllImages(property)"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <div class="property-tag" v-if="property.publishStatus === 3">安选</div>
        </div>

        <!-- 右侧内容 -->
        <div class="property-content">
          <!-- 标题行 -->
          <div class="property-header">
            <h3 class="property-title">{{ property.propertyTitle }}</h3>
            <div class="property-price">
              <span class="price">{{ property.monthlyRent }}</span>
              <span class="unit">元/月</span>
            </div>
            <!-- 添加房源状态 -->
            <el-tag
              :type="getRentStatusType(property.rentStatus)"
              size="small"
              class="rent-status-tag"
            >
              {{ getRentStatusText(property.rentStatus) }}
            </el-tag>
          </div>

          <!-- 基本信息 -->
          <div class="property-basic">
            <span>{{ property.bedroomCount }}室{{ property.livingroomCount }}厅</span>
            <span>|</span>
            <span>{{ property.area }}平米</span>
            <span>|</span>
            <span>{{ getFloorText(property) }}</span>
          </div>

          <!-- 位置信息 -->
          <div class="property-location">
            <span class="district">{{ property.district }}</span>
            <span>|</span>
            <span class="area">{{ getAreaText(property) }}</span>
            <span>|</span>
            <span class="street">{{ property.street }}</span>
          </div>

          <!-- 特色标签 -->
          <div class="property-features">
            <el-tag size="mini" v-if="property.rentType === 1">整租</el-tag>
            <el-tag size="mini" v-if="property.orientation">{{ property.orientation }}朝向</el-tag>
            <el-tag size="mini" v-if="property.hasElevator">有电梯</el-tag>
          </div>

          <!-- 房东信息 -->
          <div class="property-landlord">
            <i class="el-icon-s-custom landlord-icon"></i>
            <span class="landlord-name">{{ property.landlordName || '未知房东' }}</span>
          </div>

          <!-- 操作按钮 -->
          <div class="property-actions">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(property)"
              :disabled="!canEdit(property)"
              v-hasPermi="['system:property:edit']"
              :title="getEditButtonTitle(property)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleRent(property)"
              :disabled="!canRent(property)"
              v-hasPermi="['system:property:rent']"
              :title="getRentButtonTitle(property)"
              style="color: #67C23A;"
            >租用
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && propertyList.length === 0" class="empty-container">
        <el-empty description="暂无房源数据"/>
      </div>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房源基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 第一行：房源标题 -->
        <el-form-item label="房源标题" prop="propertyTitle">
          <el-input v-model="form.propertyTitle" placeholder="请输入房源标题" />
        </el-form-item>

        <!-- 图片上传区域 - 使用栅格布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="封面图片">
              <div class="upload-tip">封面（仅限1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="coverFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="handleCoverRemove"
                :on-change="(file, fileList) => handleCoverChange(file, fileList)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleCoverSuccess(response, file, fileList)"
                :on-error="handleUploadError"
                :limit="1"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客厅图片">
              <div class="upload-tip">客厅（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="livingRoomFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 2)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 2)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 2)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卧室图片">
              <div class="upload-tip">卧室（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="bedroomFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 3)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 3)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 3)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厨房图片">
              <div class="upload-tip">厨房（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="kitchenFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 4)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 4)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 4)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卫生间图片">
              <div class="upload-tip">卫生间（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="bathroomFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 5)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 5)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 5)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阳台图片">
              <div class="upload-tip">阳台（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="balconyFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 6)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 6)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 6)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境图片">
              <div class="upload-tip">环境（最多1张）<span style="color: #f56c6c;">*</span></div>
              <el-upload
                :action="uploadImgUrl"
                list-type="picture-card"
                :file-list="environmentFileList"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :on-remove="(file, fileList) => handleOtherRemove(file, fileList, 7)"
                :on-change="(file, fileList) => handleOtherChange(file, fileList, 7)"
                :before-upload="beforeAvatarUpload"
                :on-success="(response, file, fileList) => handleOtherSuccess(response, file, fileList, 7)"
                :on-error="handleUploadError"
                :limit="1"
                multiple
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 房源描述 -->
        <el-form-item label="房源描述" prop="propertyDesc">
          <el-input
            v-model="form.propertyDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入房源描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 地址信息 - 使用栅格布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区县" prop="district">
              <el-input v-model="form.district" placeholder="请输入区县" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="街道" prop="street">
              <el-input v-model="form.street" placeholder="请输入街道" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>

        <!-- 房屋基本信息 - 使用栅格布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月租金" prop="monthlyRent">
              <el-input v-model="form.monthlyRent" placeholder="请输入月租金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款周期" prop="paymentCycle">
              <el-select v-model="form.paymentCycle" placeholder="请选择付款周期" style="width: 100%">
                <el-option label="月付" :value="1" />
<!--                <el-option label="季付" :value="2" />-->
<!--                <el-option label="年付" :value="3" />-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input v-model="form.area" placeholder="请输入面积">
                <template slot="append">㎡</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="朝向" prop="orientation">
              <el-select v-model="form.orientation" placeholder="请选择朝向" style="width: 100%">
                <el-option label="东" value="东" />
                <el-option label="南" value="南" />
                <el-option label="西" value="西" />
                <el-option label="北" value="北" />
                <el-option label="东南" value="东南" />
                <el-option label="西南" value="西南" />
                <el-option label="东北" value="东北" />
                <el-option label="西北" value="西北" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卧室数量" prop="bedroomCount">
              <el-input-number
                v-model="form.bedroomCount"
                :min="0"
                :max="10"
                placeholder="卧室数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客厅数量" prop="livingroomCount">
              <el-input-number
                v-model="form.livingroomCount"
                :min="0"
                :max="10"
                placeholder="客厅数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在楼层" prop="floor">
              <el-input v-model="form.floor" placeholder="请输入所在楼层" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装修程度" prop="decoration">
              <el-select v-model="form.decoration" placeholder="请选择装修程度" style="width: 100%">
                <el-option label="毛坯" :value="1" />
                <el-option label="简装" :value="2" />
                <el-option label="精装" :value="3" />
                <el-option label="豪装" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否有电梯" prop="hasElevator">
              <el-select v-model="form.hasElevator" placeholder="请选择是否有电梯" style="width: 100%">
                <el-option label="有电梯" :value="1" />
                <el-option label="无电梯" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房东电话" prop="landlordPhone">
              <el-input v-model="form.landlordPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="previewVisible"
      width="60%"
      top="5vh"
      :before-close="handlePreviewClose"
    >
      <div style="text-align: center;">
        <img
          :src="previewImageUrl"
          style="max-width: 100%; max-height: 70vh; display: inline-block;"
          alt="预览图片"
        />
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="handlePreviewClose">关闭</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import { listPending, getPending, delPending, addPending, updatePending } from "@/api/system/pending"
import {listProperty, getProperty, delProperty, addProperty, updateProperty} from "@/api/system/property"
import {getToken} from "@/utils/auth"

export default {
  name: "Property",
  props: {
    action: {
      type: String,
      default: "/common/upload"
    }
  },
  data() {
    return {
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房源基础信息表格数据
      propertyList: [],
      // 弹出层标题
      title: "",
      pendingForm:{},
      // 是否显示弹出层
      open: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + this.action,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        propertyNo: null,
        propertyTitle: null,
        propertyDesc: null,
        propertyType: null,
        rentType: null,
        country: null,
        province: null,
        city: null,
        district: null,
        street: null,
        address: null,
        longitude: null,
        latitude: null,
        monthlyRent: null,
        deposit: null,
        paymentCycle: null,
        utilityBills: null,
        area: null,
        bedroomCount: null,
        livingroomCount: null,
        bathroomCount: null,
        kitchenCount: null,
        balconyCount: null,
        floor: null,
        totalFloors: null,
        orientation: null,
        decoration: null,
        hasElevator: null,
        hasParking: null,
        parkingFee: null,
        publishStatus: null,
        rentStatus: null,
        availableDate: null,
        minimumLease: null,
        maximumLease: null,
        landlordId: null,
        landlordName: null,
        landlordPhone: null,
        agencyId: null,
        agentId: null,
        viewCount: null,
        favoriteCount: null,
        contactCount: null,
        lastViewTime: null,
        publishTime: null,
        refreshTime: null,
        version: null,
        imageList: []
      },
      // 表单参数
      form: {},
      coverFileList: [],        // 封面图片列表 (类型1)
      livingRoomFileList: [],   // 客厅图片列表 (类型2)
      bedroomFileList: [],      // 卧室图片列表 (类型3)
      kitchenFileList: [],      // 厨房图片列表 (类型4)
      bathroomFileList: [],     // 卫生间图片列表 (类型5)
      balconyFileList: [],      // 阳台图片列表 (类型6)
      environmentFileList: [],  // 环境图片列表 (类型7)

      previewVisible: false,    // 预览对话框显示状态
      previewImageUrl: '',      // 预览图片URL
      // 图片类型映射
      imageTypeMap: {
        1: 'coverFileList',
        2: 'livingRoomFileList',
        3: 'bedroomFileList',
        4: 'kitchenFileList',
        5: 'bathroomFileList',
        6: 'balconyFileList',
        7: 'environmentFileList'
      },
      // 图片类型名称映射
      imageTypeNameMap: {
        1: '封面',
        2: '客厅',
        3: '卧室',
        4: '厨房',
        5: '卫生间',
        6: '阳台',
        7: '环境'
      },
      // 表单校验
      rules: {
        propertyNo: [
          {required: true, message: "房源编号不能为空", trigger: "blur"}
        ],
        propertyTitle: [
          {required: true, message: "房源标题不能为空", trigger: "blur"}
        ],
        propertyType: [
          {required: true, message: "房源类型(1:公寓 2:住宅 3:别墅 4:商铺 5:办公室)不能为空", trigger: "change"}
        ],
        rentType: [
          {required: true, message: "租赁类型(1:整租 2:合租 3:短租)不能为空", trigger: "change"}
        ],
        province: [
          {required: true, message: "省份不能为空", trigger: "blur"}
        ],
        city: [
          {required: true, message: "城市不能为空", trigger: "blur"}
        ],
        district: [
          {required: true, message: "区县不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "详细地址不能为空", trigger: "blur"}
        ],
        monthlyRent: [
          {required: true, message: "月租金不能为空", trigger: "blur"}
        ],
        utilityBills: [
          {required: true, message: "水电费承担(1:房东 2:租客 3:AA)不能为空", trigger: "blur"}
        ],
        area: [
          {required: true, message: "面积(㎡)不能为空", trigger: "blur"}
        ],
        bedroomCount: [
          {required: true, message: "卧室数量不能为空", trigger: "blur"}
        ],
        livingroomCount: [
          {required: true, message: "客厅数量不能为空", trigger: "blur"}
        ],
        decoration: [
          {required: true, message: "装修程度(1:毛坯 2:简装 3:精装 4:豪装)不能为空", trigger: "blur"}
        ],
        hasElevator: [
          {required: true, message: "是否有电梯不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    // uploadImgUrl() {
    //   return process.env.VUE_APP_BASE_API + '/common/upload';
    // }
    // 当前用户信息
    currentUser() {
      return this.$store.state.user || {};
    },

    // 当前用户ID
    currentUserId() {
      return this.currentUser.id;
    },

    // 当前用户名
    currentUserName() {
      return this.currentUser.name;
    },

    // 是否是管理员
    isAdmin() {
      return this.currentUser.roles && this.currentUser.roles.includes('admin');
    }
  },
  methods: {
    /** 获取租赁状态标签类型 */
    getRentStatusType(rentStatus) {
      const typeMap = {
        1: 'success',  // 可租 - 绿色
        2: 'info',     // 已租 - 灰色
        3: 'warning',  // 预租 - 黄色
        4: 'danger'    // 停租 - 红色
      }
      return typeMap[rentStatus] || 'info'
    },
    /** 获取租赁状态文本 */
    getRentStatusText(rentStatus) {
      const textMap = {
        1: '可租',
        2: '已租',
        3: '预租',
        4: '停租'
      }
      return textMap[rentStatus] || '未知状态'
    },
    // 判断是否可以租赁
    canRent(property) {
      // 基础条件：房源必须通过审核且处于显示状态
      if (property.auditStatus !== 1 || property.displayStatus !== 1) {
        return false;
      }

      // 检查房源是否已出租（如果有rentStatus字段）
      if (property.rentStatus === 2) { // 假设2表示已出租
        return false;
      }

      // 管理员可以操作所有房源
      if (this.isAdmin) {
        return true;
      }

      // 创建人可以操作自己创建的房源
      const isCreator = property.createBy && (
        property.createBy == this.currentUserId ||
        property.createBy === this.currentUserName
      );
      return isCreator;
    },
    // 获取租赁按钮提示信息
    getRentButtonTitle(property) {
      if (!this.canRent(property)) {
        if (property.auditStatus !== 1) {
          return '房源未通过审核，无法租赁';
        } else if (property.displayStatus !== 1) {
          return '房源未显示，无法租赁';
        } else if (property.rentStatus === 2) {
          return '房源已出租，无法再次租赁';
        } else {
          return '您没有权限操作此房源租赁';
        }
      }
      return '办理房源租赁';
    },
    // 处理租赁操作
    handleRent(property) {
      if (!this.canRent(property)) {
        if (property.rentStatus === 2) {
          this.$modal.msgWarning('该房源已出租，无法再次租赁');
        } else {
          this.$modal.msgWarning('您没有权限操作此房源租赁');
        }
        return;
      }

      // 这里可以跳转到租赁页面或打开租赁对话框
      this.$confirm('确定要为此房源办理租赁手续吗？', '确认租赁', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.processRent(property.propertyId,property.propertyTitle);
      }).catch(() => {
        // 用户取消操作
      });
    },
    // 处理租赁业务逻辑
    processRent(propertyId,propertyTitle) {
      // 或者打开租赁对话框
      this.openRentDialog(propertyId,propertyTitle);
    },
    openRentDialog(propertyId,propertyTitle) {
      // this.$modal.msgSuccess(`开始为房源 ${propertyTitle} 办理租赁手续`);
      // 这里可以打开一个租赁表单对话框
      // 在实际项目中，你可能需要：
      // 1. 打开一个对话框显示租赁表单
      // 2. 收集租客信息、租赁期限0、租金等
      // 3. 调用后端API创建租赁合同
      //TODO 未完成 如果1 发起租房 2 点击租用就会生成一份待办，
      //TODO 待办的程序则是各项内容同意了之后租房者点击了同意出租则修改房源管理的状态为已出租
      this.pendingForm={
        propertyId: propertyId,
        landlordAgreed:"1",
        tenantAgreed:"1"
      };
      addPending(this.pendingForm).then(response=>{
        this.$modal.msgSuccess("手续办理成功，请查看待办!");
      })
    },
    // 获取按钮提示信息
    getEditButtonTitle(property) {
      if (!this.canEdit(property)) {
        if (property.auditStatus === 2) {
          return '房源审核被拒绝，无法修改';
        } else if (property.auditStatus === 3) {
          return '房源审核中，无法修改';
        } else if (property.auditStatus !== 1) {
          return '房源未通过审核，无法修改';
        } else {
          return '您没有权限修改此房源';
        }
      }
      return '修改房源信息';
    },
    // 判断是否可以编辑
    canEdit(property) {

      if (property.auditStatus !== 1 || property.displayStatus !== 1) {
        console.log('❌ 房源未通过审核或未显示，无法编辑');
        return false;
      }

      // 1. 管理员可以编辑所有
      if (this.isAdmin) {
        return true;
      }
      // 2. 创建人只能编辑自己创建的房源
      // 同时检查ID和用户名匹配
      const isCreator = property.createBy && (
        property.createBy == this.currentUserId ||
        property.createBy === this.currentUserName
      );
      return isCreator;
    },
    handleCoverChange(file, fileList) {
      this.coverFileList = fileList;
    },
    // 实时检查图片完整性
    checkImageIntegrity() {
      const imageValidations = [
        { list: this.coverFileList, name: '封面图片' },
        { list: this.livingRoomFileList, name: '客厅图片' },
        { list: this.bedroomFileList, name: '卧室图片' },
        { list: this.kitchenFileList, name: '厨房图片' },
        { list: this.bathroomFileList, name: '卫生间图片' },
        { list: this.balconyFileList, name: '阳台图片' },
        { list: this.environmentFileList, name: '环境图片' }
      ];

      const missingImages = [];

      for (const validation of imageValidations) {
        const hasValidImage = validation.list.some(file => {
          const hasUrl = file.url || (file.response && file.response.url);
          return file.status === 'success' && hasUrl;
        });

        if (!hasValidImage) {
          missingImages.push(validation.name);
        }
      }

      return missingImages;
    },
    // 其他类型图片变化
    handleOtherChange(file, fileList, imageType) {
      const fileListKey = this.imageTypeMap[imageType];
      if (fileList.length > 10) {
        const typeName = this.imageTypeNameMap[imageType];
        this.$message.warning(`${typeName}图片最多只能上传10张`);
        return;
      }
      this[fileListKey] = fileList;
    },
    // 封面图片删除
    handleCoverRemove(file, fileList) {
      console.log('删除封面图片:', file);
      console.log('删除前封面文件列表:', this.coverFileList);
      this.coverFileList = fileList;
      console.log('删除后封面文件列表:', this.coverFileList);
    },
    // 其他类型图片删除
    handleOtherRemove(file, fileList, imageType) {
      console.log(`删除图片类型 ${imageType}:`, file);
      const fileListKey = this.imageTypeMap[imageType];
      console.log(`删除前 ${fileListKey}:`, this[fileListKey]);
      this[fileListKey] = fileList;
      console.log(`删除后 ${fileListKey}:`, this[fileListKey]);
    },

    // 封面图片上传成功
    handleCoverSuccess(response, file, fileList) {
      this.handleUploadSuccess(response, file, fileList, 1);
    },

    // 其他类型图片上传成功
    handleOtherSuccess(response, file, fileList, imageType) {
      this.handleUploadSuccess(response, file, fileList, imageType);
    },

    // 统一处理上传成功
    handleUploadSuccess(response, file, fileList, imageType) {
      if (response.code === 200) {
        const typeName = this.imageTypeNameMap[imageType];
        this.$message.success(`${typeName}图片上传成功`);
        // 更新文件信息
        file.url = response.url;
        file.name = response.fileName || file.name;
        // 更新对应的文件列表
        const fileListKey = this.imageTypeMap[imageType];
        this[fileListKey] = fileList.map(item => {
          if (item.uid === file.uid) {
            return {
              url: response.url,
              name: response.fileName || item.name,
              status: 'success'
            };
          }
          return item;
        });
      } else {
        this.$message.error(response.msg || '上传失败');
        // 上传失败时从文件列表中移除
        const fileListKey = this.imageTypeMap[imageType];
        this[fileListKey] = fileList.filter(item => item.uid !== file.uid);
      }
    },

    // 上传失败处理
    handleUploadError(error, file, fileList) {
      this.$message.error('图片上传失败，请重试');
      console.error('上传错误:', error);
    },

    // 或者使用更简单的方式 - 直接使用 el-image 的预览功能
    handlePreview(file) {
      console.log('Preview file:', file); // 调试信息

      // 获取图片URL - 多种方式尝试
      let imageUrl = '';

      if (file.url) {
        // 情况1: 直接有url
        imageUrl = file.url;
      } else if (file.response && file.response.url) {
        // 情况2: 从response中获取
        imageUrl = file.response.url;
      } else if (file.response && file.response.data) {
        // 情况3: 从response.data中获取
        imageUrl = file.response.data;
      } else if (file.raw) {
        // 情况4: 从raw文件中创建本地URL
        imageUrl = URL.createObjectURL(file.raw);
      }

      console.log('Image URL:', imageUrl); // 调试信息

      if (imageUrl) {
        this.previewImageUrl = imageUrl;
        this.previewVisible = true;
      } else {
        this.$message.warning('无法预览该图片');
      }
    },
    // 关闭预览
    handlePreviewClose() {
      this.previewVisible = false;
      this.previewImageUrl = '';
    },
    // 上传前校验
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是 JPG、PNG、GIF 或 WebP 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    // 构建图片列表数据（用于提交表单）
    buildImageList() {
      const imageList = [];

      // 处理所有类型的图片
      [1, 2, 3, 4, 5, 6, 7].forEach(type => {
        const fileListKey = this.imageTypeMap[type];
        const fileList = this[fileListKey];

        console.log(`处理图片类型 ${type}:`, fileList);

        fileList.forEach(file => {
          // 关键：检查文件是否真的有效
          const imageUrl = file.url || (file.response && file.response.url);
          const isFileValid = file.status === 'success' && imageUrl;

          console.log(`文件检查 - 类型${type}:`, {
            uid: file.uid,
            name: file.name,
            status: file.status,
            url: file.url,
            response: file.response,
            imageUrl: imageUrl,
            isValid: isFileValid
          });

          if (isFileValid) {
            imageList.push({
              imageType: type,
              imageUrl: imageUrl,
              fileName: file.name || `image_${type}_${Date.now()}`
            });
          }
        });
      });
      console.log('最终构建的有效图片列表:', imageList);
      return imageList;
    },

    // 设置图片文件列表（用于编辑时回显）
    setImageFileList(imageList) {
      // 清空所有文件列表
      Object.values(this.imageTypeMap).forEach(key => {
        this[key] = [];
      });

      // 根据图片类型分组设置
      imageList.forEach(image => {
        const fileListKey = this.imageTypeMap[image.imageType];
        if (fileListKey && this[fileListKey]) {
          this[fileListKey].push({
            uid: Date.now() + Math.random(),
            name: image.fileName || `image_${image.imageId}`,
            url: image.imageUrl,
            status: 'success',
            response: {
              url: image.imageUrl,
              fileName: image.fileName
            }
          });
        }
      });
    },
    // 重置所有图片列表
    resetImageLists() {
      Object.values(this.imageTypeMap).forEach(key => {
        this[key] = [];
      });
    },

    // 获取封面图片
    getCoverImage(property) {
      if (property.imageList && property.imageList.length > 0) {
        const coverImage = property.imageList.find(img => img.imageType === 1);
        const result = coverImage ? coverImage.imageUrl : property.imageList[0].imageUrl;
        return result;
      }
      return '';
    },

    // 获取所有图片用于预览
    getAllImages(property) {
      if (property.imageList && property.imageList.length > 0) {
        return property.imageList.map(img => img.imageUrl).filter(url => url);
      }
      return [];
    },

    // 获取楼层信息
    getFloorText(property) {
      if (property.floor && property.totalFloors) {
        return `${property.floor}/${property.totalFloors}层`;
      } else if (property.floor) {
        return `${property.floor}层`;
      }
      return '楼层未知';
    },

    // 获取区域信息
    getAreaText(property) {
      return [property.city, property.district].filter(Boolean).join(' | ');
    },


    getList() {
      this.loading = true
      listProperty(this.queryParams).then(response => {
        this.propertyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        propertyId: null,
        propertyNo: null,
        propertyTitle: null,
        propertyDesc: null,
        propertyType: null,
        rentType: null,
        country: null,
        province: null,
        city: null,
        district: null,
        street: null,
        address: null,
        longitude: null,
        latitude: null,
        monthlyRent: null,
        deposit: null,
        paymentCycle: null,
        utilityBills: null,
        area: null,
        bedroomCount: null,
        livingroomCount: null,
        bathroomCount: null,
        kitchenCount: null,
        balconyCount: null,
        floor: null,
        totalFloors: null,
        orientation: null,
        decoration: null,
        hasElevator: null,
        hasParking: null,
        parkingFee: null,
        publishStatus: null,
        rentStatus: null,
        availableDate: null,
        minimumLease: null,
        maximumLease: null,
        landlordId: null,
        landlordName: null,
        landlordPhone: null,
        agencyId: null,
        agentId: null,
        viewCount: null,
        favoriteCount: null,
        contactCount: null,
        lastViewTime: null,
        publishTime: null,
        refreshTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        version: null,
        imageList: []
      };
      // 清空图片列表
      this.coverFileList = [];
      this.livingRoomFileList = [];
      this.bedroomFileList = [];
      this.kitchenFileList = [];
      this.bathroomFileList = [];
      this.balconyFileList = [];
      this.environmentFileList = [];
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.propertyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加房源基础信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!this.canEdit(row)) {
        if (row.auditStatus === 2) {
          this.$modal.msgWarning('房源审核被拒绝，无法修改');
        } else if (row.auditStatus === 3) {
          this.$modal.msgWarning('房源审核中，无法修改');
        } else if (row.auditStatus !== 1) {
          this.$modal.msgWarning('房源未通过审核，无法修改');
        } else {
          this.$modal.msgWarning('您没有权限修改此房源');
        }
        return;
      }
      this.reset()
      const propertyId = row.propertyId || this.ids
      console.log("row",row);
      console.log("propertyId",propertyId);
      getProperty(propertyId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改房源基础信息"
        // 设置图片回显
        this.setImageFileList(response.data.imageList || [])
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 验证所有类型图片是否至少上传了一张
      const imageValidations = [
        { list: this.coverFileList, name: '封面图片', type: 1 },
        { list: this.livingRoomFileList, name: '客厅图片', type: 2 },
        { list: this.bedroomFileList, name: '卧室图片', type: 3 },
        { list: this.kitchenFileList, name: '厨房图片', type: 4 },
        { list: this.bathroomFileList, name: '卫生间图片', type: 5 },
        { list: this.balconyFileList, name: '阳台图片', type: 6 },
        { list: this.environmentFileList, name: '环境图片', type: 7 }
      ];

      console.log('=== 图片验证开始 ===');

      // 使用 buildImageList 来验证，因为它会过滤无效文件
      const validImageList = this.buildImageList();
      console.log('有效图片列表:', validImageList);

      // 检查每种类型是否都有有效图片
      const missingTypes = [];

      for (const validation of imageValidations) {
        const hasValidImage = validImageList.some(img => img.imageType === validation.type);
        console.log(`${validation.name} (类型${validation.type}) 是否有有效图片:`, hasValidImage);

        if (!hasValidImage) {
          missingTypes.push(validation.name);
        }
      }

      if (missingTypes.length > 0) {
        this.$message.error(`请上传以下图片: ${missingTypes.join('、')}`);
        return;
      }

      console.log('✅ 所有图片验证通过');

      this.$refs["form"].validate(valid => {
        if (valid) {
          const imageList = this.buildImageList();
          this.form.imageList = imageList;
          if (this.form.propertyId != null) {
            updateProperty(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProperty(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const propertyIds = row.propertyId || this.ids
      this.$modal.confirm('是否确认删除房源基础信息编号为"' + propertyIds + '"的数据项？').then(function () {
        return delProperty(propertyIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/property/export', {
        ...this.queryParams
      }, `property_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>


<style scoped>

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.property-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.property-card {
  display: flex;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: box-shadow 0.3s;
}

.property-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.property-image {
  position: relative;
  width: 200px;
  height: 200px;
  flex-shrink: 0;
}

.property-image .el-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.property-tag {
  position: absolute;
  top: 8px;
  left: 8px;
  background: #ff4d4f;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
}

.property-content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.property-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.property-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  flex: 1;
  margin-right: 12px;
}

.property-price {
  text-align: right;
  flex-shrink: 0;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.unit {
  font-size: 12px;
  color: #666;
}

.property-basic {
  margin-bottom: 8px;
  font-size: 13px;
  color: #666;
}

.property-basic span {
  margin-right: 8px;
}

.property-location {
  margin-bottom: 8px;
  font-size: 13px;
  color: #666;
}

.property-location span {
  margin-right: 8px;
}

.district {
  color: #409EFF;
  font-weight: 500;
}

.property-features {
  margin-bottom: 8px;
}

.property-features .el-tag {
  margin-right: 6px;
  margin-bottom: 4px;
}

.property-landlord {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.landlord-prefix {
  color: #409EFF;
  font-weight: 500;
}

.landlord-name {
  margin-left: 2px;
}

.property-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.empty-container {
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .property-card {
    flex-direction: column;
  }

  .property-image {
    width: 100%;
    height: 200px;
  }

  .property-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .property-price {
    margin-top: 8px;
  }
}

/* 表单整体样式 */
.el-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

/* 自定义滚动条 */
.el-form::-webkit-scrollbar {
  width: 6px;
}

.el-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.el-form::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.el-form::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 上传组件样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
  margin-top: -5px;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 18px;
}

/* 行间距 */
.el-row {
  margin-bottom: 5px;
}

/* 对话框底部按钮 */
.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #e8e8e8;
  background: #fafafa;
}

/* 数字输入框样式 */
.el-input-number {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .el-col {
    margin-bottom: 10px;
  }
}
.property-landlord {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.landlord-icon {
  margin-right: 6px;
  color: #409EFF; /* 蓝色图标 */
  font-size: 14px;
}

.landlord-name {
  margin-left: 2px;
}

/* 或者使用深色图标 */
.landlord-icon.dark {
  color: #606266;
}

/* 或者使用主题色 */
.landlord-icon.primary {
  color: #409EFF;
}

/* 或者使用成功色 */
.landlord-icon.success {
  color: #67C23A;
}
/* 租赁按钮特殊样式 */
.property-actions .rent-button {
  color: #67C23A;
}

.property-actions .rent-button:hover {
  color: #85ce61;
  background-color: #f0f9eb;
}

/* 操作按钮容器调整 */
.property-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px; /* 增加按钮间距 */
}


</style>
